#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File        :   151.翻转字符串里的单词.py    
@Contact     :   lhouctcs@163.com
@License     :   MIT
@Time        :   2023/2/8 15:17
@Author      :   lhou 
@Version     :   0.1.0
@Description :
"""


# import lib
class Solution:
    def reverseWords(self, s: str) -> str:
        # 去除前空格
        s = self.strip(s)
        l = []
        item = ""
        for i in s:
            if i == " ":
                if item == "": continue
                l.append(item)
                item = ""
            else:
                item += i
        l.append(item)
        left = 0
        right = len(l) - 1
        while left <= right:
            l[left], l[right] = l[right], l[left]
            left += 1
            right -= 1
        newStr = ""
        for i in l:
            newStr += i + " "
        return self.strip(newStr)

    def strip(self, s):
        i = 0
        while s[i] == " ": i += 1
        s = s[i:]
        i = len(s) - 1
        while s[i] == " ": i -= 1
        s = s[:i + 1]
        return s
